import 'package:easy_refresh/easy_refresh.dart';
import 'package:safetymonitor/app/components/common/no_permissions_widget.dart';
import 'package:safetymonitor/app/components/custom_app_bar.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_multiple_bottom_sheet.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/components/video/ijk_player.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/ext.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/http/network_manger.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/data/entities/application/corporation_name_entity.dart';
import 'package:safetymonitor/app/data/entities/application/get_device_info_entity.dart';
import '../../../app/components/custom_modele/custom_cardx.dart';

/// 视频监控
class VideoMonitor extends StatefulWidget {
  const VideoMonitor({super.key});

  @override
  State<VideoMonitor> createState() => _VideoMonitorState();
}

class _VideoMonitorState extends State<VideoMonitor> {
  List<CorporationNameEntity> _nameList = [];

  /// 选中的公司
  CorporationNameEntity? _selectId;

  /// 获取信息列表(视频和点位名字)
  List<GetDeviceInfoEntity> _infoList = [];


  final TextEditingController _controller = TextEditingController();

  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _getDepartmentList();
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!isNotPermissions) {
      return const NoPermissionsWidget();
    }

    return Scaffold(
      backgroundColor: const Color(0xffF7FBFE),
      appBar: CustomAppBar(
        titleText: '视频监控',
      ),
      body: Padding(
        padding: const EdgeInsets.only(
          top: 16,
          left: 16,
          right: 16,
        ),
        child: Column(
          children: [
            _buildSelect(),
            AppGaps.vGap16,
            Expanded(
              child: _buildVideoList(),
            ),
          ],
        ),
      ),
    );
  }

  // 视频播放item``
  Widget _buildVideoItem(GetDeviceInfoEntity infoList) {
    return CustomCardX(
      onTap: () {
        if (NetworkManager.netWorkInfo == NetWorkInfo.intranet.name) {
          _toDetails(infoList.videoStream, infoList.deviceName ?? '视频播放');
        } else {
          _toDetails(infoList.outNetAddress, infoList.deviceName ?? '视频播放');
        }
      },
      child: Row(
        children: [
          Container(
            height: 50.w,
            width: 50.w,
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.circular(6),
            ),
            alignment: Alignment.center,
            child: Icon(Icons.video_camera_back, size: 28, color: Colors.white),
          ),
          AppGaps.hGap10,
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  infoList.deviceName ?? '',
                  style: TextStyle(
                    color: const Color(0xff3D4769),
                    fontSize: 15.w,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                AppGaps.vGap2,
                Text(
                  infoList.systemName ?? '',
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 14.w,
                  ),
                ),
              ],
            ),
          ),
          // const Spacer(),
          Icon(Icons.play_circle, size: 28),
          AppGaps.hGap6,
        ],
      ),
    );
  }

  Widget _buildVideoList() {
    return _infoList.isNotEmpty
        ? EasyRefresh(
            onRefresh: () {},
            child: ListView.separated(
              itemCount: _infoList.length,
              itemBuilder: (context, index) {
                return Container(child: _buildVideoItem(_infoList[index]));
              },
              separatorBuilder: (context, index) {
                return AppGaps.vGap16;
              },
            ),
          )
        : Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SvgPicture.asset('assets/svg/zhiban_empty_bg.svg'),
                Text(
                  '暂无内容',
                  style: TextStyle(
                    color: const Color(0xFFC7CEE5),
                    fontSize: 14.sp,
                  ),
                ),
                AppGaps.vGap40,
              ],
            ),
          );
  }

  Widget _buildSelect() {
    return Row(
      children: [
        Expanded(
          child: Container(
            height: AppDimens.dp32,
            decoration: BoxDecoration(color: Colors.white, border: Border.all(color: const Color(0xffDCE1EA)), borderRadius: BorderRadius.circular(6)),
            child: Row(
              children: [
                AppGaps.hGap8,
                SvgPicture.asset(
                  'assets/svg/icon_search.svg',
                  width: 16.w,
                ),
                Expanded(
                  child: TextField(
                    keyboardType: TextInputType.text,
                    textInputAction: TextInputAction.done,
                    controller: _controller,
                    focusNode: _focusNode,
                    onChanged: (value) {
                      _getDeviceList();
                    },
                    style: TextStyle(color: const Color(0xff222222), fontWeight: FontWeight.w400, fontSize: 14.sp),
                    decoration: InputDecoration(
                      counterText: '',
                      //防止适配不居中
                      isCollapsed: true,
                      border: const OutlineInputBorder(borderSide: BorderSide.none),
                      contentPadding: EdgeInsets.only(left: 8.w),
                      hintText: '请输入监控名称',
                      hintStyle: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.w400, color: const Color(0xffA0A7B5)),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
        AppGaps.hGap16,
        Expanded(
          child: Container(
            height: AppDimens.dp32,
            decoration: BoxDecoration(color: Colors.white, border: Border.all(color: const Color(0xffDCE1EA)), borderRadius: BorderRadius.circular(6)),
            child: Row(
              children: [
                const SizedBox(
                  width: 12,
                ),
                Expanded(
                    child: Text(
                  _getString(),
                  style: TextStyles.grey_14,
                  maxLines: 1,
                )),
                const Icon(
                  Icons.keyboard_arrow_down,
                  color: AppColors.font_color_gray,
                ),
                const SizedBox(
                  width: 8,
                ),
              ],
            ),
          ).clickOnce(() {
            _selectCompany();
          }),
        ),
      ],
    );
  }

  // 跳转详情
  void _toDetails(String? url, String title) {
    if (url.isNullOrEmpty) {
      AppToast.showError('视频地址为空');
      return;
    }
    if (url!.startsWith('ws')) {
      url = url.replaceFirst('ws', 'http');
    }
    Get.to(() => IjkPlayerPage(
          url: url!,
          title: title,
        ));
  }

  String _getString() {
    if (_selectId != null) {
      return _selectId?.name ?? '';
    }
    return '公司名';
  }

  // 获取部门列表
  void _getDepartmentList() async {
    final res = await HttpUtil().generateGetRequest<List<CorporationNameEntity>>(Interface.deptList, queryParameters: {
      'flag': 2,
      'appType': 1,
    }).execute();

    res.onSuccess((result) {
      if (result.data != null) {
        _nameList = result.data!;
        //获取第一个
        _selectId = _nameList.first;
        _getDeviceList();
      }
    });
  }

  // 选取公司
  void _selectCompany() {
    CustomEquipmentBottomSheet<CorporationNameEntity>(
      dataList: _nameList,
      checkedList: _selectId != null ? [_selectId!] : [],
      onConfirm: (value) {
        if (value.isNotEmpty) {
          _selectId = value[0];
          _controller.clear();
          _focusNode.unfocus();
          _getDeviceList();
        }
      },
      title: '选择公司',
      isMultiple: false,
    ).showBottomSheetDialog();
  }

  ///视频缩略图 从视频文件在内存中生成缩略图
  // Future<Uint8List> getThumbnail(String videoPath) async {
  // final thumbnail = await VideoThumbnail.thumbnailData(
  //   video: videoPath,
  //   imageFormat: ImageFormat.JPEG,
  //   quality: 100,
  // );
  // return thumbnail!;
  // }
  bool isNotPermissions = true;

  //获取设备列表
  void _getDeviceList() async {
    _infoList.clear();
    final res = await HttpUtil().generateGetRequest<List<GetDeviceInfoEntity>>(Interface.getDeviceList, queryParameters: {
      'companyId': _selectId?.id,
      'deviceTypeCode': 'camera', //设备编码，camera-摄像头
      'deviceName': _controller.text,
    }).execute(isShowLoading: true);

    res.onSuccess((result) {
      if (result.data != null) {
        _infoList = result.data!;
      }
      isNotPermissions = true;
      setState(() {});
    });
    res.onError((result) {
      if (result.code == 403 && result.message == '没有该操作权限') {
        isNotPermissions = false;
        setState(() {});
      }
    });
  }
}
